<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
        <el-form-item label="水源地名称" prop="status">
            <el-input v-model="queryParams.drinksourcename" placeholder="请输入水源地名称" />
        </el-form-item>
        <el-form-item label="取水口名称" prop="status">
            <el-input v-model="queryParams.segmentname" placeholder="请输入取水口名称" />
        </el-form-item>
        <el-form-item label="取水口类型">
            <el-select v-model="queryParams.segmentcategory" placeholder="请选取水口类型" clearable>
                <el-option v-for="item in dict.type.syd_intake_type" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
            </el-select>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
            <el-button
            type="primary"
            plain 
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            >新增</el-button>
        </el-col>
        <el-col :span="1.5">
            <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            @click="handleDelete(null)"
            >删除</el-button>
        </el-col>
        <!-- <el-col :span="1.5">
            <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            >导出</el-button>
        </el-col> -->
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
        <el-table style="width: 100%" :data="tableData" v-loading="loading" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="饮用水源地名称" prop="drinksourcename" />
            <el-table-column label="取水口名称" prop="segmentname" />
            <el-table-column label="一级保护区面积（Km²）" prop="firstprotectarea"  />
            <el-table-column label="二级保护区面积（Km²）" prop="secondprotectarea"  />
            <el-table-column label="取水口类型" prop="segmentcategory"  >
                <template #default="{ row }">
                    {{row.segmentcategory | dictType(dict.type.syd_intake_type)}}
                </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="120" align="center">
                <template #default="{ row }">
                <el-button size="mini" type="text" @click="handleEdit(row)">修改</el-button>
                <el-button size="mini" type="text" @click="handleDelete(row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
            v-show="total>0"
            :current-page="queryParams.pageNum"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="queryParams.pageSize"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            :pager-count="5"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            >
      </el-pagination>
        <el-dialog :title="title" :visible.sync="dialogVisible" v-if="dialogVisible" width="900px" append-to-body>
            <el-form ref="formRef" :model="formData" label-width="140px" size="small" :rules="formRules">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="水源地名称" prop="drinksourceid">
                            <el-select v-model="formData.drinksourceid" placeholder="请选择水源地名称" filterable clearable style="width: 100%;" @change="formChange($event,'id',{'drinksourcename':'drinksourcename'},drinkList)">
                                <el-option
                                v-for="item in drinkList"
                                :key="item.id"
                                :label="item.drinksourcename"
                                :value="item.id"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="取水口编码" prop="segmentcode">
                            <el-input v-model="formData.segmentcode" placeholder="请输入取水口编码" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="取水口名称" prop="segmentname">
                            <el-input v-model="formData.segmentname" placeholder="请输入取水口名称" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="取水口类型" prop="segmentcategory">
                            <el-select v-model="formData.segmentcategory" placeholder="请选择取水口类型" filterable clearable style="width: 100%;">
                                <el-option
                                v-for="item in dict.type.syd_intake_type"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="一级保护区面积" prop="firstprotectarea">
                            <el-input v-model="formData.firstprotectarea" placeholder="请输入一级保护区面积"  >
                                <template slot="append">（Km²）</template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="一级保护区描述" prop="primarydescribe">
                            <el-input v-model="formData.primarydescribe" type="textarea" :rows="3" placeholder="请输入一级保护区描述" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="二级保护区面积" prop="secondprotectarea">
                            <el-input v-model="formData.secondprotectarea" placeholder="请输入二级保护区面积"  >
                                <template slot="append">（Km²）</template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="二级保护区描述" prop="secondarydescribe">
                            <el-input v-model="formData.secondarydescribe" type="textarea" :rows="3" placeholder="请输入二级保护区描述" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="准保护区面积" prop="quasiprotectarea">
                            <el-input v-model="formData.quasiprotectarea" placeholder="请输入准保护区面积"  >
                                <template slot="append">（Km²）</template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="准保护区描述" prop="quasidescribe">
                            <el-input v-model="formData.quasidescribe" type="textarea" :rows="3" placeholder="请输入准保护区描述" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row >
                    <el-col :span="12">
                        <el-form-item label="经度" prop="longitude">
                            <el-input v-model="formData.longitude" placeholder="请输入经度" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="纬度" prop="latitude">
                            <el-input v-model="formData.latitude" placeholder="请输入纬度" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row >
                    <el-col :span="12">
                        <el-form-item label="启用时间" prop="startdate">
                            <el-date-picker
                                style="width: 100%;"
                                v-model="formData.startdate"
                                type="date"
                                placeholder="请选择启用时间"
                                value-format="yyyy-MM-dd"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="停用时间" prop="enddate">
                            <el-date-picker
                                style="width: 100%;"
                                v-model="formData.enddate"
                                type="date"
                                placeholder="请选择停用时间"
                                value-format="yyyy-MM-dd"
                            />
                        </el-form-item>
                    </el-col>
                </el-row>
                  <el-tabs v-model="activeName" @tab-click="tabHandleClick">
                        <el-tab-pane label="一级保护区" name="oneProtectInfle">
                            <intakeTab ref="oneProtectInfleRef" :list="formData.oneProtectInfle"></intakeTab>
                        </el-tab-pane>
                        <el-tab-pane label="二级保护区" name="twoProtectInfle">
                            <intakeTab ref="twoProtectInfleRef" :list="formData.twoProtectInfle"></intakeTab>
                        </el-tab-pane>
                        <el-tab-pane label="准保护区" name="protectInfle">
                            <intakeTab ref="protectInfleRef" :list="formData.protectInfle"></intakeTab>
                        </el-tab-pane>
                    </el-tabs>
            </el-form>
            <div slot="footer">
                <el-button @click="clsoeForem">取 消</el-button>
                <el-button type="primary" @click="submitForm">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
    import {getIntakeList,removeIntake,addIntake,editIntake} from './api/waterintake';
    // import {validatorLongitude,validatorLatitude} from '@/utils/validate';
    import {getdrinksourcelist} from './api/baseinfo'
    import intakeTab from './components/intakeTab.vue';
    export default {
        name: "waterSourceIntake",
        components:{
            intakeTab
        },
        props:{
            nodeid:{
                type:String,
                default:""
            }
        },
        dicts: ["syd_intake_type"],
        data(){
            return {
                // 遮罩层
                loading: false,
                // 显示搜索条件
                showSearch: true,
                total:0,
                queryParams:{
                    pageNum:1,
                    pageSize:10,
                },
                regionList:[],
                tableData:[],
                drinkList:[],
                selectedRows:[],
                dialogVisible:false,
                formRules:{
                    drinksourceid: [{ required: true, message: '请选择水源地名称', trigger: 'change' }],
                    segmentname: [{ required: true, message: '请输入取水口名称', trigger: 'blur' }],
                    // segmentcode: [{ required: true, message: '请输入取水口编码', trigger: 'blur' }],
                    segmentcategory: [{ required: true, message: '请选择取水口类型', trigger: 'change' }],
                },
                formData:{},
                activeName:"oneProtectInfle"
            }  
        },
        computed:{
            title(){
                return (this.formData.id ? '编辑' : '新增') + '取水口'
            }
        },
        filters:{
            dictType(value,list){
                let item = list.find(it => it.value==value);
                return item?item.label:"";
            },
        },
        created(){
            this.getList();
            this.getdrinksourcelistFn();
        },
        methods:{
            formChange(value,key,map,list){
                let item = list.find(it => it[key]==value);
                if(item) {
                    for(let fkey in map){
                    this.formData[fkey] = item[map[fkey]]
                    }
                }
            },
           handleQuery(){
            this.getList();
           },
           resetQuery(){
            this.queryParams = {
                pageNum:1,
                pageSize:10,
            };

           },
           handleSizeChange(val){
            this.queryParams.pageSize = val;
            this.getList();
           },
           handleCurrentChange(val){
            this.queryParams.pageNum = val;
            this.getList();
           },
           handleAdd(){
            this.formData = 
            {
                "segmentname": "",
                "segmentcode": "",
                "segmentcategory": "",
                "drinksourcename": "",
                "drinksourceid": "",
                "longitude": "",
                "latitude": "",
                "startdate": "",
                "enddate": "",
                "introduction": "",
                "primarydescribe": "",
                "secondarydescribe": "",
                "quasidescribe": "",
                "firstprotectarea": "",
                "secondprotectarea": "",
                "quasiprotectarea": "",
                "oneProtectInfle": [],
                "twoProtectInfle": [],
                "protectInfle": []
            };
            this.dialogVisible = true;
           },
           handleEdit(row = {}){
            this.formData = {...row};
            console.log(this.formData)
            this.dialogVisible = true;
            this.$nextTick(() => {
                this.$refs['formRef'].resetFields();
            })
           },
           async handleDelete(row){
                let ids = [];
                if(row){
                    ids.push(row.id);
                } else {
                    ids = this.selectedRows.map(item => item.id);
                }
                if(!ids[0]){
                    return this.$message.warning('请选择要删除的行');
                }
                let res = await this.$confirm(`确定删除吗？`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    return true
                }).catch(() => {
                    return false
                });
                if(res) {
                    await removeIntake(ids.join(','))
                    this.$message.success('删除成功')
                    this.getList()
                }
           },
           async submitForm(){ 
            let res = await this.formValidate();
            if(!res){
                this.clsoeForem();
                return
            }
            let oneProtectInfle = await this.$refs.oneProtectInfleRef.validateAll(); 
            if(!oneProtectInfle) {
                this.clsoeForem()
                return
            }
            let twoProtectInfle = await this.$refs.twoProtectInfleRef.validateAll();
            if(!twoProtectInfle){
                this.clsoeForem()
                return
            }
            let protectInfle = await this.$refs.protectInfleRef.validateAll();
            if(!protectInfle){
                this.clsoeForem()
                return
            }           
            this.formData.oneProtectInfle = [...oneProtectInfle]
            this.formData.twoProtectInfle = [...twoProtectInfle]
            this.formData.protectInfle = [...protectInfle];
            if(this.formData.id) {await editIntake(this.formData)
                this.$message.success('修改成功')
            } else {
                await addIntake(this.formData)
                this.$message.success('新增成功')
            }
            this.getList();
            this.clsoeForem()
           },
           formValidate(){
                return new Promise((resolve,reject) => {
                    this.$refs["formRef"].validate(valid => {
                        if(valid){
                            resolve(true)
                        }else{
                            reject(false)
                        }
                    })
                })
           },
           clsoeForem(){
             this.$refs['formRef'].resetFields();
             this.formData = {}
             this.dialogVisible = false;
           },
           async getList(){
             this.loading = true;
             let params = {...this.queryParams}
             console.log("params", this.nodeid)
             if (this.nodeid) {
                params.drinksourceid = this.nodeid;
             }
             let res = await getIntakeList(params);
             this.tableData = res.rows;
             this.total = res.total;
             this.loading = false;
           },
           async getdrinksourcelistFn(){
            let res = await getdrinksourcelist();
            this.drinkList = res.rows;
           },
            handleSelectionChange(selection){
                this.selectedRows = selection;
            },
            tabHandleClick(tab, event){
                console.log(tab, event);
            },

        }
    }
</script>